# _*_ coding:utf-8 _*_
# @File  : ruizy_menu.py
# @Time  : 2022-01-10  13:45
# @Author: zizle
""" 接口转移文件预废弃 """

import datetime
from fastapi import APIRouter, Header
from hutool import security
from db import FAConnection
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import data_utils, datetime_utils

menu_api = APIRouter()

# 首页。这也是菜单数据结构的标准(由前端写上)
# INDEX_MENU = {
#     'path': '/',
#     'component': 'Layout',
#     'redirect': 'index',
#     'children': [
#         {
#             'path': 'index',
#             'name': 'Index',
#             'component': '@/views/index/index',
#             'meta': {
#                 'title': '首页',
#                 'icon': 'home',
#                 'affix': True
#             }
#         }
#     ]
# }


# @menu_api.post('/menu/navigate/')  # 用户获取菜单
async def menu_list(ruizy_token: str = Header(...)):
    def handle_menu_meta(m):
        if m['parent_code'] == 0:  # parent_code=0是顶级navbar，不用设置这些
            return m
        m['meta'] = {
            'title': m['menu_name'],
            'icon': m['icon'],
            'permissions': m['permissions']  # 控制菜单的访问权限
        }
        m['name'] = m['vue_name']
        del m['vue_name']
        del m['icon']
        del m['permissions']
        if not m['redirect']:
            del m['redirect']
        return m

    def filter_user_menus(item, role, vip_date):
        item['permissions'] = ['admin', 'free', 'vip']
        # today = datetime.datetime.today().strftime('%Y-%m-%d')
        # authorization = True
        # if item.get('expire') and item['expire'].strftime('%Y-%m-%d') < today:
        #     authorization = False
        # if role == 'vip' and vip_date.strftime('%Y-%m-%d') >= today:
        #     item['permissions'] = ['free', 'vip']
        #     authorization = True
        return True

    user_payload = security.decrypt_access_token(ruizy_token)
    if not user_payload:
        return AllResponse.no_authorization(data=[])

    db_conn = FAConnection()
    # 查用户角色，请求角色下的菜单
    user_sql = "SELECT id,role,role_code,vip_expire FROM ruizy_user WHERE id=%s;"
    user_obj = db_conn.query(user_sql, param=[user_payload['uid']], fetchone=True, keep_conn=True)[0]
    if not user_obj:
        db_conn.close()
        return AllResponse.no_authorization()
    if user_obj['role_code'] == 9999:  # 查询所有
        sql = """
            SELECT a.id,a.menu_code,a.menu_name,a.parent_code,a.category,a.vue_name,a.component,a.icon,a.path,
            a.redirect,a.hidden,a.sorted 
            FROM ruizy_menu As a WHERE a.is_active=1 
            ORDER BY a.sorted,a.id;
        """
        prm = None
        special_sql = ''
        special_prm = None
    else:  # 查询角色下的菜单
        sql = """
            SELECT b.id,b.menu_code,b.menu_name,b.parent_code,b.category,b.vue_name,b.component,b.icon,b.path,
            b.redirect,b.hidden,b.sorted,a.expire 
            FROM ruizy_role_menu As a 
            INNER JOIN ruizy_menu As b ON a.menu_code=b.menu_code AND b.is_active=1 
            WHERE a.role_code=%s AND a.expire>=%s 
            ORDER BY b.sorted,b.id;
        """
        prm = [user_obj['role_code'], datetime_utils.today(f='%Y-%m-%d')]

        special_sql = """
            SELECT m.id,m.menu_code,m.menu_name,m.parent_code,m.category,m.vue_name,m.component,m.icon,m.path,m.redirect,
                m.hidden,m.sorted,um.expire  
            FROM ruizy_user_menu As um 
            INNER JOIN ruizy_menu As m ON um.menu_code=m.menu_code AND um.user_id=%s 
            WHERE um.expire>=%s AND m.is_active=1;
        """
        special_prm = [user_obj['id'], datetime_utils.today(f='%Y-%m-%d')]

    records = db_conn.query(sql, param=prm, keep_conn=True)

    # 查询用户的特别菜单
    if special_sql:
        special_menu = db_conn.query(special_sql, special_prm)
        if special_menu:
            # 合并菜单
            records_ids = [r['id'] for r in records]
            special_list = [sm for sm in special_menu if sm['id'] not in records_ids]  # 取出不存在的
            records.extend(special_list)  # 合并特别设置的菜单
            records.sort(key=lambda x: (x['sorted'], x['id']))  # 排序
    else:
        db_conn.close()

    # 过滤菜单（根据user_role和分配的情况）
    records = filter(lambda x: filter_user_menus(x, user_obj['role'], user_obj['vip_expire']), records)
    records = list(map(handle_menu_meta, records))
    menus = data_utils.list2tree(records, pkey='parent_code', ckey='menu_code', fvalue='0')
    # import json
    # with open('menu.json', 'w', encoding='utf-8') as fp:
    #     json.dump(menus, fp, indent=2,ensure_ascii=False)
    return AllResponse.operate_successfully(data=menus)

""" 文件预废弃 """
